/**
 *  @file FindMinValueAndDel.c
 *  @desc TODO 描述该文件的功能
 *  @author WangBlue(wangjiping596@gmail.com)
 *  @date 2025-07-24 10:23
 *  @version 1.0
 */


#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <time.h>


typedef struct node {
    int data;
    struct node *next;
}node, *link;

link createNode(int value) {
    link newNode = (link) malloc (sizeof(node));
    if (newNode == NULL) return NULL;
    newNode->data = value;
    newNode->next = NULL;
    return newNode;
}

void initNode(link *head) {
    link newNode = createNode(0);
    if (newNode == NULL) return;
    *head = newNode;
    newNode->next = *head;
}

void istHead(link head, int value) {
    link newNode = createNode(value);
    if (newNode == NULL) return;

    newNode->next = head->next;
    head->next = newNode;
}

void istTail(link head ,int value) {
    link newNode = createNode(value);
    if (newNode == NULL) return;
    link cur = head;
    while (cur->next != head) {
        cur = cur->next;
    }
    cur->next = newNode;
    newNode->next = head;
}

void printList(link head) {
    if (head == NULL || head->next == head) return;
    link cur = head->next;
    while (cur != head) {
        printf("value is %d\n", cur->data);
        cur = cur->next;
    }
    printf("\n");
}

void istByPos(link head, int pos, int value) {
    if (head == NULL || head->next == head || pos < 1) return;
    link cur = head;
    int idx = 1;
    while (cur->next != head && idx < pos ) {
        cur = cur->next;
        idx ++;
    }

    if (idx != pos ) return;
    link newNode = createNode(value);
    if (newNode == NULL) return;

    newNode->next = cur->next;
    cur->next = newNode;
}

void delByPos(link head, int pos) {
    if (head == NULL || head->next == NULL || pos < 1) return;
    link cur = head->next;
    link pre = head;
    int idx = 1;
    while (cur != head && idx < pos ) {
        pre = cur;
        cur = cur->next;
        idx ++;
    }
    if (cur->next == head) return;
    pre->next = cur->next;
    free(cur);
}

void findMinValueAndDel(link *head) {
    if (head == NULL || (*head)->next == *head) return;

    while ((*head)->next != *head) {
        link cur = (*head)->next;
        link minNode = cur;
        link preA = *head;
        while (cur != *head) {
            if (minNode->data > cur->data) {
                preA = minNode;
                minNode = cur;
            }
            cur = cur->next;
        }

        printf("minValue is %d\n", minNode->data);
        preA->next = minNode->next;
        free(minNode);
    }
    free(*head);
    *head = NULL;
}

int main() {
    link head = NULL;
    initNode(&head);
    istTail(head, 1);
    istTail(head, 3);
    istTail(head, 2);
    findMinValueAndDel(&head);
    printList(head);
}